﻿using Games.Basic;
using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;

namespace Games.Common
{
    class GamePageManager
    {
        protected readonly Regex AssemblyExcludeRegex;
        private const string ASSEMBLY_EXCLUDE_PATTERN = @"^System|^mscorlib|^Microsoft|^CppCodeProvider|^VJSharpCodeProvider|^WebDev
                                                        |^Nuget|^Castle|^Iesi|^log4net|^Autofac|^AutoMapper|^EntityFramework|^xunit|^nunit
                                                        |^TestDriven|^MbUnit|^Rhino|^QuickGraph|^TestFu|^Telerik|^Antlr3|^Recaptcha|^FluentValidation
                                                        |^ImageResizer|^itextsharp|^MiniProfiler|^Newtonsoft|^Pandora|^WebGrease|^Noesis|^DotNetOpenAuth
                                                        |^Facebook|^LinqToTwitter|^PerceptiveMCAPI|^CookComputing|^GCheckout|^Mono\.Math|^Org\.Mentalis
                                                        |^App_Web|^BundleTransformer|^ClearScript|^JavaScriptEngineSwitcher|^MsieJavaScriptEngine|^Glimpse
                                                        |^Ionic|^App_GlobalResources|^AjaxMin|^MaxMind|^NReco|^OffAmazonPayments|^UAParser";
        public GamePageManager()
        {
            AssemblyExcludeRegex = new Regex(ASSEMBLY_EXCLUDE_PATTERN, RegexOptions.IgnoreCase | RegexOptions.Compiled | RegexOptions.Singleline);
        }
        public IEnumerable<IGameInfo> GetAllGames()
        {
            var list = new List<IGameInfo>();
            var itType = typeof(IGameInfo);
            var asss = AppDomain.CurrentDomain.GetAssemblies();
            foreach(var ass in asss)
            {
                if(AssemblyExcludeRegex.IsMatch(ass.FullName))
                {
                    continue;
                }
                try
                {
                    var types = ass.GetTypes();
                    foreach(var type in types)
                    {
                        if(type.IsClass && !type.IsAbstract && itType.IsAssignableFrom(type))
                        {
                            try
                            {
                                var gm = (IGameInfo)Activator.CreateInstance(type);
                                list.Add(gm);
                            }
                            catch(Exception)
                            {
                                //ignore
                            }
                        }
                    }
                }
                catch(Exception)
                {
                    //ignore
                }
            }
            return list;
        }
    }
}